<?php
/**
 * @since v1.0
 * @modify 2015.6.21
 * @copyright 深圳亿游
 */
require_once(LIB_PATH.'controller/root.con.php');

class fileCon extends rootCon
{
    public function uploadAction(){
         // Undefined | Multiple Files | $_FILES Corruption Attack
        // If this request falls under any of them, treat it invalid.
        if (
            !isset($_FILES['upfile']['error']) ||
            is_array($_FILES['upfile']['error'])
        ) {
            $this->j(-6,'参数错误！');
        }

        // Check $_FILES['upfile']['error'] value.
        switch ($_FILES['upfile']['error']) {
            case UPLOAD_ERR_OK:
                break;
            case UPLOAD_ERR_NO_FILE:
                $this->j(-5,'您没有上传图片');
            case UPLOAD_ERR_INI_SIZE:
            case UPLOAD_ERR_FORM_SIZE:
                $this->j(-4,'图片大小错误');
            default:
                $this->j(-9,'未知错误');
        }

        // You should also check filesize here.
        if ($_FILES['upfile']['size'] > 10000000) {
            $this->j(-3,'您上传的图片太大了');
        }

        // DO NOT TRUST $_FILES['upfile']['mime'] VALUE !!
        // Check MIME Type by yourself.
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        if (false === $ext = array_search(
                $finfo->file($_FILES['upfile']['tmp_name']),
                array(
                    'jpg' => 'image/jpeg',
                    'png' => 'image/png',
                    'gif' => 'image/gif',
                ),
                true
            )) {
            $this->j(-2,'文件类型错误');
        }

        // You should name it uniquely.
        // DO NOT USE $_FILES['upfile']['name'] WITHOUT ANY VALIDATION !!
        // On this example, obtain safe unique name from its binary data.
        $imageSavedName = sprintf('up/%s.%s',
            sha1_file($_FILES['upfile']['tmp_name']),
            $ext
        );

        if (!move_uploaded_file(
            $_FILES['upfile']['tmp_name'],
            ROOT_PATH.'web/'.$imageSavedName
        )) {
            $this->j(-1,'系统错误！');
        }

        //创建缩略图
        myimage::resize(ROOT_PATH.'web/'.$imageSavedName,90,1);

        $imageFile = new ImageFile();
        $imageFile->uid = mylogin::getUid(false);
        $imageFile->uploadImg = FRONT_URL.$imageSavedName;
        $imageFile->ip = myrequest::getIP();
        $imageFile->created = date('Y-m-d H:i:s');
        $imageFile->save();

        $this->j(0,'upload',['imageFileId'=>$imageFile->imageFileId]);
    }


}



